package jalus.blog;

import jalus.Action;
import jalus.model.BlogLink;
import jalus.service.BlogLinkService;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;

import com.google.appengine.api.datastore.Link;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class BlogLinkServlet extends Action {
	
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)	throws IOException {
		String action = req.getParameter("action");
		if(StringUtils.equalsIgnoreCase(action, "new")){
			newBlogLink(req, resp);
		}else if(StringUtils.equalsIgnoreCase(action, "delete")){
			deleteBlogLink(req, resp);
		}else{
			error();
			return;
		}

	}
	
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		doGet(req, resp);
	}
	
	private void deleteBlogLink(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		if(!userService.isUserLoggedIn() || !userService.isUserAdmin()){
			error();
			return;
		}
		
		long id = NumberUtils.toLong(req.getParameter("delid"));
		if(id == 0){
			error();
			return;
		}
		BlogLinkService blogLinkService = BlogLinkService.getInstance();
		blogLinkService.deleteById(id);
		resp.sendRedirect(req.getHeader("Referer"));
	}

	private void newBlogLink(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		if(!userService.isUserLoggedIn() || !userService.isUserAdmin()){
			error();
			return;
		}
		
		Link url = new Link(req.getParameter("url"));
		String text = req.getParameter("text");
		String description = req.getParameter("description");
		BlogLink blogLink = new BlogLink(url, text, description);
		BlogLinkService blogLinkService = BlogLinkService.getInstance();
		blogLinkService.add(blogLink);		
		
		resp.sendRedirect(req.getHeader("Referer"));
	}


}
